package top.jiangqiang.qyblog.core.service;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import top.jiangqiang.qyblog.common.base.query.PageResult;
import top.jiangqiang.qyblog.common.base.response.Result;
import top.jiangqiang.qyblog.common.id.IDGenerator;
import top.jiangqiang.qyblog.core.base.service.BaseService;
import top.jiangqiang.qyblog.core.domain.dto.BatchUploadFileDto;
import top.jiangqiang.qyblog.core.domain.dto.FileQueryDto;
import top.jiangqiang.qyblog.core.domain.dto.UploadByUrlDto;
import top.jiangqiang.qyblog.core.domain.dto.UploadFileDto;
import top.jiangqiang.qyblog.core.domain.entity.File;
import top.jiangqiang.qyblog.core.domain.vo.BatchUploadFileVo;
import top.jiangqiang.qyblog.core.domain.vo.FileVo;
import top.jiangqiang.qyblog.core.domain.vo.UploadByUrlVo;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author JiangQiang
 * @since 2023-05-23
 */
public interface IFileService extends BaseService<File> {

    Result<FileVo> uploadFile(UploadFileDto uploadFileDto);

    Result<BatchUploadFileVo> uploadFiles(BatchUploadFileDto batchUploadFileDto);

    Result<UploadByUrlVo> uploadFileByUrl(UploadByUrlDto uploadByUrlDto);

    Result<FileVo> getFileDetail(Long id);

    Result<Boolean> deleteFile(Long id);

    /**
     * 生成全局唯一的fileKey
     *
     * @param fileName 原始文件名
     * @return
     */
    default String genFileKey(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            return genFileKeyByExtName(null);
        } else {
            String extName = FileNameUtil.extName(fileName);
            return genFileKeyByExtName(extName);
        }
    }

    /**
     * 根据扩展名获取key
     * 如果扩展名为空字符串，则获取到一个全局唯一id
     *
     * @param extName 扩展名
     * @return
     */
    default String genFileKeyByExtName(String extName) {
        IDGenerator idGenerator = SpringUtil.getBean(IDGenerator.class);
        if (StrUtil.isBlank(extName)) {
            return idGenerator.nextUUID();
        } else {
            return idGenerator.nextUUID() + "." + extName;
        }
    }

    PageResult<FileVo> findByCondition(FileQueryDto query);
}
